package com.atguigu.springcloud.payment.controller;

import com.atguigu.springcloud.framework.common.api.ApiResult;
import com.atguigu.springcloud.payment.entity.Payment;
import com.atguigu.springcloud.payment.service.PaymentService;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * @author lenovo
 * @version 1.0
 * @date 2020/11/11 11:07
 */
@Api(value = "支付")
@Slf4j
@RestController
@RequestMapping("payment")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class PaymentController {

    final private PaymentService paymentService;


    @Value("${server.port}")
    private Integer port;

    @PostMapping("create")
    public ApiResult create(@RequestBody Payment payment) {
        boolean save = paymentService.save(payment);
        log.info("插入的结果【{}】", save);
        return ApiResult.result(save);
    }


    @GetMapping("get/{id}")
    public ApiResult query(@PathVariable("id") Long id) {
        Payment payment = paymentService.getById(id);
        log.info("查询的结果【id={}】【{}】", id, payment);
        return ApiResult.ok(payment).setMessage("端口：" + port);
    }

    @GetMapping("lb")
    public String lb() {
        return "lb:" + port;
    }

    /**
     * 模拟业务处理超时请求接口（处理时间过长-即模拟超时请求接口）
     *
     * @return
     */
    @GetMapping("feign/timeout")
    public String timeout() {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start("feign-timeout");
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        stopWatch.stop();
        long totalTimeMillis = stopWatch.getTotalTimeMillis();
        log.info("耗时【{}】", totalTimeMillis);
        return "端口：" + port + "耗时【" + totalTimeMillis + "】";
    }


    @GetMapping("zipkin")
    public String zipkin() {
        return "hi,i' am payment zipkin server fall back, welcome to atguigu, 0(n. n)0哈哈~";
    }

}
